package changedb;


import java.io.File;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;

/**
 *
 *
 * @author Ben Goodwin
 * @version @version 2.0 16/09/2011
 */
public class Open {

    public static File open() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
        }
        JFileChooser open = new JFileChooser();
        open.setFileFilter(new XMLFilter());
        int choose = open.showOpenDialog(null);
        if (choose == JFileChooser.APPROVE_OPTION) {
            File currentFile = open.getSelectedFile();
            return currentFile;
        } else {
            return null;
        }
    }

    public static String read(File selectedFile, MembersList ml) {
        try {
            ArrayList<Member> members = new ArrayList<Member>();
            Builder builder = new Builder();
            Document data = builder.build(selectedFile);
            Element root = data.getRootElement();
            if (root.getLocalName().equals("database") || root.getLocalName().equals("databaseEncrypted")) {
                Elements entries = root.getChildElements();
                for (int index = 0; index < entries.size(); index++) {
                    Element e = entries.get(index);
                    Elements info = e.getChildElements();
                    ArrayList<String> details = new ArrayList<String>();
                    for (int c = 0; c < info.size(); c++) {
                        Element det = info.get(c);
                        if(root.getLocalName().equals("databaseEncrypted")) {
                            details.add(x.decrypt(det.getValue()));
                        }
                        else {
                            details.add(det.getValue());
                        }
                    }
                    Member m = new Member(details.get(0), details.get(1), details.get(2), details.get(3),
                            details.get(4), details.get(5), details.get(6), details.get(7), details.get(8),
                            details.get(9), details.get(10), details.get(11), details.get(12), details.get(13),
                            details.get(14), details.get(15), details.get(16), details.get(17));
                    members.add(m);
                }
                ml.setList(members);
            } else {
                return "Error - This isn't a valid database file: " + selectedFile + ".";
            }
        } catch (Exception e) {
            return "Error - Read of " + selectedFile + " failed.";
        }
        return "Read of file " + selectedFile + " successful!";
    }
}
